package com.badibadi.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.badibadi.abcpinying.CharacterParser;
import com.badibadi.abcpinying.ClearEditText;
import com.badibadi.abcpinying.PinyinComparator;
import com.badibadi.abcpinying.PinyinComparator_Friends;
import com.badibadi.abcpinying.SideBar;
import com.badibadi.abcpinying.SortModel;
import com.badibadi.abcpinying.SideBar.OnTouchingLetterChangedListener;
import com.badibadi.infos.MyFriendsModel;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.FriendsTool;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.ViewHolder;
import com.badibadi.uniclubber.R;
import com.libjph.util.JsonUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

//@好友
public class MyFriendsResultActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {
	private Button myfriendresult_back;// 返回
	private Button myfriendresult_index;// 完成
	private XListView xListView;
	private Results results;
	private int Page;
	private List<MyFriendsModel> list;
	private MyFriendResult_Adapter adapter;
	private SideBar sideBar;
	private TextView dialog;
	private CheckBox myfriendresult_checkall;
	private ClearEditText myfriendresult_edit;
	private String uid;// 登录的用户
	/**
	 * 临时存储@的好友名字
	 */
	// public static Map<Integer, String> strings = new HashMap<Integer,
	// String>();
	public List<MyFriendsModel> friendsModels;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator_Friends pinyinComparator;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(MyFriendsResultActivity.this);
					Utils.showMessage(MyFriendsResultActivity.this,
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				offload();
				break;
			case 2:
				try {
					Utils.ExitPrgress(MyFriendsResultActivity.this);
				} catch (Exception e) {
					   
				}
				// Constants.friendsModels.addAll(list);
				// Constants.friendsModels =
				// filledData(Constants.friendsModels);
				friendsModels.addAll(list);
				friendsModels = filledData(friendsModels);
				// 根据a-z进行排序源数据
				Collections.sort(friendsModels, pinyinComparator);
				adapter.notifyDataSetChanged();
				offload();
				break;
			case 3:
				try {

					Utils.ExitPrgress(MyFriendsResultActivity.this);
					Utils.showMessage(MyFriendsResultActivity.this,
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
				}
				offload();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		goToTheTitle();
		setContentView(R.layout.myfriendresult_main);
		uid = Utils.getUid(MyFriendsResultActivity.this);
		Page = 0;
		init();
	}

	private void init() {
		myfriendresult_back = (Button) findViewById(R.id.myfriendresult_back);
		myfriendresult_checkall = (CheckBox) findViewById(R.id.myfriendresult_checkall);
		myfriendresult_edit = (ClearEditText) findViewById(R.id.myfriendresult_edit);
		friendsModels = new ArrayList<MyFriendsModel>();
		// Constants.strings = new HashMap<Integer, String>();
		myfriendresult_index = (Button) findViewById(R.id.myfriendresult_index);
		adapter = new MyFriendResult_Adapter(friendsModels,
				getApplicationContext());
		xListView = (XListView) findViewById(R.id.myfriendresult_list);
		xListView.setXListViewListener(this);
		xListView.setPullLoadEnable(true);
		xListView.setPullRefreshEnable(true);
		xListView.setAdapter(adapter);
		xListView.startLoadMore();
		myfriendresult_back.setOnClickListener(this);
		myfriendresult_index.setOnClickListener(this);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator_Friends();
		sideBar = (SideBar) findViewById(R.id.myfriendresult_sidrbar);
		dialog = (TextView) findViewById(R.id.myfriendresult_dialog);
		sideBar.setTextView(dialog);

		myfriendresult_edit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				filterData(arg0.toString());
				// if (arg0.toString().length() > 0) {
				// onRefresh();
				// }
				if (arg0.toString().length() == 0) {
					onRefresh();
				}

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}
		});

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
//				   ("出现位置:" + s.charAt(0));
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					xListView.setSelection(position);
				}
			}
		});
		myfriendresult_checkall
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean arg1) {
						// TODO Auto-generated method stub
						if (arg1) {
							adapter.setAllcheck_OK();
						} else {
							adapter.setAllcheck_NO();
						}
					}
				});
	}

	private void Friends(final String id, final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<MyFriendsModel>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", id);
				map.put("page", page);
				map.put("pageNum", 10);
				// String content = Utils.sendRequest(map, Constants.BadiUrl
				// + "friends");
				String content = Utils.getRequest(Constants.BadiUrl
						+ "friends?uid=" + id + "&page=" + page + "&pageNum="
						+ 10);
//				   
				//    (Constants.BadiUrl + "friends?uid=" + id
				// + "&page=" + page + "&pageNum=" + 10);
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    ("@好友结果是:" + results.getRetmsg());
//						   
						try {
							list = JsonUtil.getListByJsonString(
									results.getRetmsg(), MyFriendsModel.class);
							handler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						handler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private void offload() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.setRefreshTime(""
				+ getResources().getString(R.string.ganggang));
	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<MyFriendsModel> filterDateList = new ArrayList<MyFriendsModel>();
		// 是否为空
		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = friendsModels;
		} else {
			filterDateList.clear();
			for (MyFriendsModel sortModel : friendsModels) {
				String name = sortModel.getNickName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.myfriendresult_back:// 返回
			if (friendsModels.size() > 0) {
				friendsModels.clear();
			}
			this.finish();
			break;
		case R.id.myfriendresult_index:// 完成
			Intent it = new Intent();
			it.putExtra("result", (Serializable) friendsModels);
			setResult(3, it);
			finish();
			break;

		default:
			break;
		}
	}

	private class MyFriendResult_Adapter extends BaseAdapter {
		private DisplayImageOptions options;

		public MyFriendResult_Adapter(List<MyFriendsModel> friendsModels,
				Context context) {
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		/**
		 * 当ListView数据发生变化时,调用此方法来更新ListView
		 * 
		 * @param list
		 */
		public void updateListView(List<MyFriendsModel> list) {
			friendsModels = list;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return friendsModels.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return friendsModels.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			// LayoutInflater inflater = LayoutInflater.from(context);
			// arg1 = inflater.inflate(R.layout.myfriendresult_item, null);
			if (arg1 == null) {
				arg1 = ViewHolder.buildView(getApplicationContext(),
						R.layout.myfriendresult_item, arg2);
			}
			ViewHolder viewHolder = (ViewHolder) arg1.getTag();
			final ImageView myfriendresult_item_head = viewHolder
					.getViewById(R.id.myfriendresult_item_head);
			RelativeLayout myfriendresult_item_rel = viewHolder
					.getViewById(R.id.myfriendresult_item_rel);
			TextView myfriendresult_item_name = viewHolder
					.getViewById(R.id.myfriendresult_item_name);
			final CheckBox myfriendresult_item_ok = viewHolder
					.getViewById(R.id.myfriendresult_item_ok);
			//    ("图片地址是:" + Constants.BadiDownImgUrl
			// + friendsModels.get(arg0).getHead());
			ImageLoader.getInstance().displayImage(
					Constants.BadiDownImgUrl
							+ friendsModels.get(arg0).getHead()
							+ Constants.appPhoto4img, myfriendresult_item_head,
					options);
			// ImageLoader.getInstance().loadImage(
			// Constants.BadiDownImgUrl
			// + friendsModels.get(arg0).getHead()+Constants.appPhoto4img,
			// options,
			// new ImageLoadingListener() {
			//
			// @Override
			// public void onLoadingStarted(String arg0, View arg1) {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void onLoadingFailed(String arg0, View arg1,
			// FailReason arg2) {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void onLoadingComplete(String arg0, View arg1,
			// Bitmap arg2) {
			// // double dd1 = itemWidth
			// // / ((double) ((float) (arg2.getWidth()) / arg2
			// // .getHeight()));
			// myfriendresult_item_head.setImageBitmap(Utils
			// .scaleImg(arg2, 94, 94));
			// }
			//
			// @Override
			// public void onLoadingCancelled(String arg0, View arg1) {
			// // TODO Auto-generated method stub
			//
			// }
			// });
			myfriendresult_item_name.setText(friendsModels.get(arg0)
					.getNickName());
			myfriendresult_item_ok
					.setChecked(friendsModels.get(arg0).isJudge());
			myfriendresult_item_rel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg012) {
					if (myfriendresult_item_ok.isChecked()) {
						myfriendresult_item_ok.setChecked(false);
						friendsModels.get(arg0).setJudge(false);
						// Constants.strings.put(arg0, null);
					} else {
						myfriendresult_item_ok.setChecked(true);
						friendsModels.get(arg0).setJudge(true);
						// Constants.strings.put(arg0, "@"
						// + Constants.friendsModels.get(arg0)
						// .getNickName() + " ");
					}
				}
			});
			myfriendresult_item_ok.setFocusable(false);
			myfriendresult_item_ok.setFocusableInTouchMode(false);

			myfriendresult_item_head.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (friendsModels.get(arg0).getId() != null) {
						if (friendsModels
								.get(arg0)
								.getId()
								.equals(""
										+ Utils.getUid(MyFriendsResultActivity.this))) {
							Intent intent = new Intent(
									MyFriendsResultActivity.this,
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(
									MyFriendsResultActivity.this,
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", friendsModels
									.get(arg0).getId());
							startActivity(intent);
						}

					}

				}
			});
			myfriendresult_item_name.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (friendsModels.get(arg0).getId() != null) {
						if (friendsModels
								.get(arg0)
								.getId()
								.equals(""
										+ Utils.getUid(MyFriendsResultActivity.this))) {
							Intent intent = new Intent(
									MyFriendsResultActivity.this,
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(
									MyFriendsResultActivity.this,
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", friendsModels
									.get(arg0).getId());
							startActivity(intent);
						}

					}

				}
			});
			return arg1;
		}

		// /**
		// * 根据ListView的当前位置获取分类的首字母的Char ascii值
		// */
		// public int getSectionForPosition(int position) {
		// return friendsModels.get(position).getSortLetters().charAt(0);
		// }

		/**
		 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
		 */
		public int getPositionForSection(char section) {
			for (int i = 0; i < friendsModels.size(); i++) {
				String sortStr = friendsModels.get(i).getSortLetters();
				char firstChar = sortStr.toUpperCase().charAt(0);
				if (firstChar == section) {
					return i;
				}
			}
			return -1;
		}

		public void setAllcheck_OK() {
			for (int i = 0; i < friendsModels.size(); i++) {
				friendsModels.get(i).setJudge(true);
				// Constants.strings.put(i, "@"
				// + Constants.friendsModels.get(i).getNickName() + " ");
				notifyDataSetChanged();
			}
		}

		public void setAllcheck_NO() {
			for (int i = 0; i < friendsModels.size(); i++) {
				friendsModels.get(i).setJudge(false);
				// Constants.strings.put(i, "@"
				// + Constants.friendsModels.get(i).getNickName() + " ");
				notifyDataSetChanged();
			}
		}

	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<MyFriendsModel> filledData(List<MyFriendsModel> friends) {
		List<MyFriendsModel> friendsModels = new ArrayList<MyFriendsModel>();

		for (int i = 0; i < friends.size(); i++) {
			MyFriendsModel sortModel = new MyFriendsModel();
			sortModel.setNickName(friends.get(i).getNickName());
			sortModel.setHead(friends.get(i).getHead());
			sortModel.setId(friends.get(i).getId());
			sortModel.setMotto(friends.get(i).getMotto());
			sortModel.setJudge(false);
			sortModel.setIs_firend(friends.get(i).getIs_firend());
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(friends.get(i)
					.getNickName());
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}
			friendsModels.add(sortModel);
		}
		return friendsModels;

	}

	// /**
	// * 根据输入框中的值来过滤数据并更新ListView
	// *
	// * @param filterStr
	// */
	// private void filterData(String filterStr) {
	// List<SortModel> filterDateList = new ArrayList<SortModel>();
	// // 是否为空
	// if (TextUtils.isEmpty(filterStr)) {
	// filterDateList = SourceDateList;
	// } else {
	// filterDateList.clear();
	// for (SortModel sortModel : SourceDateList) {
	// String name = sortModel.getName();
	// if (name.indexOf(filterStr.toString()) != -1
	// || characterParser.getSelling(name).startsWith(
	// filterStr.toString())) {
	// filterDateList.add(sortModel);
	// }
	// }
	// }
	//
	// // 根据a-z进行排序
	// Collections.sort(filterDateList, pinyinComparator);
	// adapter.updateListView(filterDateList);
	// }
	//
	// /**
	// * 根据输入框中的值来过滤数据并更新ListView
	// *
	// * @param filterStr
	// */
	// private void filterData(String filterStr) {
	// List<SortModel> filterDateList = new ArrayList<SortModel>();
	// // 是否为空
	// if (TextUtils.isEmpty(filterStr)) {
	// filterDateList = SourceDateList;
	// } else {
	// filterDateList.clear();
	// for (SortModel sortModel : SourceDateList) {
	// String name = sortModel.getName();
	// if (name.indexOf(filterStr.toString()) != -1
	// || characterParser.getSelling(name).startsWith(
	// filterStr.toString())) {
	// filterDateList.add(sortModel);
	// }
	// }
	// }
	//
	// // 根据a-z进行排序
	// Collections.sort(filterDateList, pinyinComparator);
	// adapter.updateListView(filterDateList);
	// }

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		friendsModels.clear();
		Page = 1;

		Friends(uid, Page);

	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

		Friends(uid, ++Page);

	}

}
